package com.ruoyi.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.DraftArticle;
import com.ruoyi.service.IDraftArticleService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 草稿文章Controller
 * 
 * @author ruoyi
 * @date 2025-09-13
 */
@RestController
@RequestMapping("/article/draft")
public class DraftArticleController extends BaseController
{
    @Autowired
    private IDraftArticleService draftArticleService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询草稿文章列表
     */
    //@PreAuthorize("@ss.hasPermi('article:draft:list')")
    @GetMapping("/list")
    public TableDataInfo list(DraftArticle draftArticle)
    {
        startPage();
        List<DraftArticle> list = draftArticleService.selectDraftArticleList(draftArticle);
        return getDataTable(list);
    }

    /**
     * 导出草稿文章列表
     */
    //@PreAuthorize("@ss.hasPermi('article:draft:export')")
    @Log(title = "草稿文章", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DraftArticle draftArticle)
    {
        List<DraftArticle> list = draftArticleService.selectDraftArticleList(draftArticle);
        ExcelUtil<DraftArticle> util = new ExcelUtil<DraftArticle>(DraftArticle.class);
        util.exportExcel(response, list, "草稿文章数据");
    }

    /**
     * 获取草稿文章详细信息
     */
    //@PreAuthorize("@ss.hasPermi('article:draft:query')")
    @GetMapping(value = "/{articleId}")
    public AjaxResult getInfo(@PathVariable("articleId") Long articleId)
    {
        return success(draftArticleService.selectDraftArticleByArticleId(articleId));
    }

    /**
     * 新增草稿文章
     */
    //@PreAuthorize("@ss.hasPermi('article:draft:add')")
    @Log(title = "草稿文章", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DraftArticle draftArticle)
    {
        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        // 设置创建者信息
        draftArticle.setCreateBy(sysUser.getUserName());
        draftArticle.setUpdateBy(sysUser.getUserName());

        // 设置创建时间和更新时间
        Date now = new Date();
        draftArticle.setCreateTime(now);
        draftArticle.setUpdateTime(now);

        // 如果没有设置pubdate，则使用当前日期
        if (draftArticle.getPubdate() == null || draftArticle.getPubdate().isEmpty()) {
            // 格式化日期为字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            draftArticle.setPubdate(sdf.format(now));
        }
        System.out.println("草稿箱内容："+draftArticle);

        return toAjax(draftArticleService.insertDraftArticle(draftArticle));
    }

    /**
     * 修改草稿文章
     */
    //@PreAuthorize("@ss.hasPermi('article:draft:edit')")
    @Log(title = "草稿文章", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DraftArticle draftArticle)
    {
        // 获取当前登录用户信息
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();

        // 设置更新者信息
        draftArticle.setUpdateBy(sysUser.getUserName());

        // 设置更新时间
        Date now = new Date();
        draftArticle.setUpdateTime(now);

        // 如果没有设置pubdate，则使用当前日期
        if (draftArticle.getPubdate() == null || draftArticle.getPubdate().isEmpty()) {
            // 格式化日期为字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            draftArticle.setPubdate(sdf.format(now));
        }

        return toAjax(draftArticleService.updateDraftArticle(draftArticle));
    }

    /**
     * 删除草稿文章
     */
    //@PreAuthorize("@ss.hasPermi('article:draft:remove')")
    @Log(title = "草稿文章", businessType = BusinessType.DELETE)
    @DeleteMapping("/{articleIds}")
    public AjaxResult remove(@PathVariable Long[] articleIds)
    {
        return toAjax(draftArticleService.deleteDraftArticleByArticleIds(articleIds));
    }

    /**
     * 发布草稿文章
     */
    //@PreAuthorize("@ss.hasPermi('article:draft:edit')")
    @Log(title = "草稿文章", businessType = BusinessType.UPDATE)
    @PostMapping("/publish/{articleId}")
    public AjaxResult publish(@PathVariable Long articleId)
    {
        try {
            return toAjax(draftArticleService.publishDraftArticle(articleId));
        } catch (RuntimeException e) {
            return error(e.getMessage());
        }
    }
}